package com.zzvcom.office.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.zzvcom.office.cfg.SimpleConfig;
import com.zzvcom.office.exception.OfficeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URISyntaxException;

/**
 * 限制简单实现
 */
@Component
@Slf4j
public class LimitUtil {
    @Autowired
    private SimpleConfig simpleConfig;

    /**
     * 仅仅服务规定范围的文件下载,转码浏览
     * @param url
     */
    public  String  validateUrl(String url) {
        java.net.URI uri = null;
        try {
            uri = new java.net.URI(url);
            String host = uri.getHost();
            boolean isAllowFlag = false;
            if (CollUtil.isNotEmpty(simpleConfig.getAllowFileDomainSuffix())) {
                for (String s : simpleConfig.getAllowFileDomainSuffix()) {
                    if (host.endsWith(s)) {
                        isAllowFlag = true;
                        break;
                    }
                }
                if (!isAllowFlag) {
                    log.error("不允许host={}", host);
                    log.error("allowFileDomainSet={}", simpleConfig.getAllowFileDomainSuffix());
                    throw new OfficeException("不允许");
                }
            }
        } catch (URISyntaxException e) {
            log.error("url={}", url);
            log.error("url error:", e);
           throw new OfficeException("url格式错误");
        }
        //title在在最后进行项目特殊情况的处理
        url=CommonUtil.justUrl(url);
        return url;
    }

    /**
     * 验证编辑器运行的操作
     * @param action
     */
    public void validateAction(String action){
        if(CollUtil.isEmpty(simpleConfig.getAllowAction())){
            return;
        }

        if(!simpleConfig.getAllowAction().contains(action)){
            log.error("不允许action={}", action);
            log.error("allowActionSet={}", simpleConfig.getAllowAction());
            throw new OfficeException("不允许的action="+action);
        }

    }


    public void validateOp(String op){
        if(CollUtil.isEmpty(simpleConfig.getAllowOp())){
            return;
        }
        if(!simpleConfig.getAllowOp().contains(op)){
            log.error("不允许op={}", op);
            log.error("allowOpSet={}", simpleConfig.getAllowOp());
            throw new OfficeException("不允许,op="+op);
        }
    }

}
